package org.bing.engine.controller.helper;


public class StringHelper {
    public static char PROPERTY_PREFIX = '$';

    public static String replaceWithProperty(String s, String src, String dest) {
        int len = s.length();
        int bf = -1, ef = -1;
        StringBuffer sb = new StringBuffer();
        char last = ' ';
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c == '{' && last == PROPERTY_PREFIX) {
                bf = i;
                ef = -1;
            } else if (c == '}') {
                if (bf >= 0) { // hit property
                    ef = i;
                    String key = sb.toString();
                    if (src.equalsIgnoreCase(key)) {
                        StringBuffer tb = new StringBuffer();
                        return tb.append(s.substring(0, bf - 1)).append(dest).append(s.substring(ef + 1)).toString();
                    }
                } else {
                    bf = -1;
                    ef = -1;
                }
            } else {
                if (bf >= 0) {
                    sb.append(c);
                }
            }
            last = c;
        }
        return s;
    }

    public static String getProperty(String src) {
        int len = src.length();
        int bf = -1;
        StringBuffer sb = new StringBuffer();
        char last = ' ';
        for (int i = 0; i < len; i++) {
            char c = src.charAt(i);
            if (c == '{' && last == PROPERTY_PREFIX) {
                bf = i;
            } else if (c == '}') {
                if (bf >= 0) {
                    String key = sb.toString();
                    return key;
                } else {
                    bf = -1;
                }
            } else {
                if (bf >= 0) {
                    sb.append(c);
                }
            }
            last = c;
        }
        return null;
    }
}
